package com.yy.utils;

/**
 * @Description:
 * @ClassName: AESDecrypter
 * @author: 姚欣宏
 * @date: 2023.11.01
 */
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class AESDecrypter {
    private static final String KEY = "hxgy_jkmh_abcdef";  // AES key & IV

    public static void main(String[] args) {
        String encryptedString = "ovbR/JjAx8iUAuDfKGz2MoLzfRVd9rtcTcB2GaM3TQtz+h7KbYvLkAEcEe7qVEs/uKIzbBlcV9vOFxy4Vj6rLIT3NTwOFTyu7KbtLqRzzdxhcrEMslWU9iicKx7ugal8MsoqG7BjUZqgktrnM3TtZykQM10dZOSzy2JFmHrPwXGNFf/37iZGgv1km9EN3kxYcep+pEJu32ClsG2HluhmLC3rKBKQkg28LM2JBKStwEOfI/k/FOZGk5H2hmOy0jhJIIY+QX9W7BwfoMn8d8oFaHzBULSwWrGRUENUZsE7ANQXpIana2l99hCKuLgZZ7QYIl0eLjl8CNzHq+BgyLmI+dKdveeA/SRvfNB1RsqqDfDIjVRzsRdGFSB5LGo+mVuYLi994/CfNDK0ygU9dUG9q/PhYuNhjO73xhmUgAqscZI=";
        String decryptedString = decrypt(encryptedString, KEY, KEY);
        System.out.println(decryptedString);
    }

    public static String decrypt(String encrypted, String key, String initVector) {
        try {
            IvParameterSpec iv = new IvParameterSpec(initVector.getBytes(StandardCharsets.UTF_8));
            SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
            byte[] original = cipher.doFinal(Base64.getDecoder().decode(encrypted));
            return new String(original, StandardCharsets.UTF_8);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }
}
